package com.cloud.feeling.ststem.utils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cloud.common.CommonConstants;

public class JwtHelper {

	private static final String SECRET = "session_secret";

	private static final String ISSUER = "feelj_user";

	public static String genToken(Map<String, String> claims) {
		try {
			Algorithm algorithm = Algorithm.HMAC256(SECRET);
			JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER)
					.withExpiresAt(DateUtils.addDays(new Date(), 1));
			claims.forEach((k, v) -> builder.withClaim(k, v));
			return builder.sign(algorithm).toString();
		} catch (IllegalArgumentException | UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	public static Map<String, String> verifyToken(String token) {
		Algorithm algorithm = null;
		try {
			algorithm = Algorithm.HMAC256(SECRET);
		} catch (IllegalArgumentException | UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
		DecodedJWT jwt = verifier.verify(token);
		Map<String, Claim> map = jwt.getClaims();
		Map<String, String> resultMap = new HashMap<>();
		map.forEach((k, v) -> resultMap.put(k, v.asString()));
		return resultMap;
	}
	
	/**
	 * 校验请求中是否有 cookie
	 * @param request
	 * @return
	 */
	public static String Checktoken(HttpServletRequest request) {
		String cookie = request.getParameter(CommonConstants.TOKEN_COOKIE);
		if(cookie!=null&&StringUtils.isNoneEmpty(cookie)) {
		}else {
			cookie = request.getHeader(CommonConstants.TOKEN_COOKIE);
		}
		return cookie;
    }

}
